import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: 'login',
    component: () =>
      import(/* webpackChunkName: 'login' */ "@/views/Login.vue"),
  },
  {
    path: "/",
    component: ()=>import('@/layout/index.vue'),
    children: [
      {
        path: "",
        name: 'home',
        component: () =>
          import(/* webpackChunkName: 'home' */ "@/views/Home.vue"),
      },
      {
        path: "setting",
        name: 'setting',
        component: () =>
          import(/* webpackChunkName: 'setting' */ "@/views/Setting.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL, //vue脚手架配置中的publicPath
  routes,
});

// 添加路由守卫，路由拦截

// 全局路由守卫，路由一旦开始工作，进入任何的路径，都需要进入这个拦截的函数。
router.beforeEach((to, from, next)=>{
  // to: 进入的路径信息对象。
  // from: 离开的路径信息对象。
  // next();进入
  // next(false);路由进入失败
  // next('/login');重定向到其他路径
  // next({name: 'login'});重定向到其他路径

  if(to.name === 'login'){
    //进入登录页面
    next();
  }else{
    const token = localStorage.getItem('TOKEN');
    if(token){
      //校验token是否有效
      //.............
      next();
    }else{
      next({name: 'login'});
    }
  }
})


export default router;
